package com.heying.xmlandjson.dom4j;

import com.heying.xmlandjson.entity.Note;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class NoteXml {

    private  Document xmlDoc;

    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

    public NoteXml(){
        try {
        //classpath的绝对路径
        String classpath = ClassLoader.getSystemResource("").getPath();
        File xmlFile = new File(classpath+"note.xml"); //输入输出流中文件对象关联路径
        SAXReader reader = new SAXReader();
        this.xmlDoc = reader.read(xmlFile);//解析文档(看源代码)
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Note query(){
        //获得根元素
        Element noteEl =  xmlDoc.getRootElement();
        String to = noteEl.elementText("to");
        String from = noteEl.elementText("from");
        String heading = noteEl.elementText("heading");
        String body = noteEl.elementText("body");
        return new Note(to, from, heading, body);
    }

    public void updateFrom(String newFrom) throws IOException {
        Element noteEl = xmlDoc.getRootElement();
        noteEl.element("from").setText(newFrom);
        output();
    }

    public void addDate(Date date) throws IOException {
        Element noteEl = xmlDoc.getRootElement();
        noteEl.addElement("date").setText(simpleDateFormat.format(date));
        output();
    }

    public void delDate() throws IOException {
        Element noteEl = xmlDoc.getRootElement();
        noteEl.remove(noteEl.element("date"));
        output();
    }

    public void output() throws IOException {
        File xmlFile = new File("note.xml");
        FileWriter fw = new FileWriter(xmlFile);
        OutputFormat format = OutputFormat.createCompactFormat();
        format.setEncoding("UTF-8");
        XMLWriter writer = new XMLWriter(fw,format);
        writer.write(xmlDoc);
        writer.close();
    }


    public static void main(String[] args) throws Exception {

       NoteXml noteXml = new NoteXml();
//        System.out.println(noteXml.query());
//        noteXml.updateFrom("Tom");
        noteXml.addDate(new Date());
//        noteXml.delDate();



    }
}
